import React, { useMemo, useState } from 'react';
import { View, StyleSheet, Switch } from 'react-native';
import { Layout, UI, useThemeColors, Feedback } from '@gaozh1024/rn-toolkit';
import type { DialogType, DialogAction } from '@gaozh1024/rn-toolkit/lib/components/feedback/Dialog/DialogService';

const { Dialog } = Feedback;

const typeList: DialogType[] = ['info', 'warning', 'error', 'success'];

const DialogTestScreen: React.FC = () => {
    const colors = useThemeColors();

    const styles = StyleSheet.create({
        section: { marginBottom: 16 },
        row: { flexDirection: 'row', alignItems: 'center', gap: 12, flexWrap: 'wrap' },
        col: { gap: 12 },
        card: { borderRadius: 12, borderWidth: 1, borderColor: colors.border },
        bordered: { borderWidth: 1, borderColor: colors.border, borderRadius: 8, padding: 12 },
    });

    // 行为与样式配置
    const [cancelable, setCancelable] = useState<boolean>(false);
    const [blocking, setBlocking] = useState<boolean>(true); // 当前容器始终阻塞（pointerEvents='auto'），此项传入但可能不生效
    const [maskColor, setMaskColor] = useState<string>('rgba(0,0,0,0.45)');
    const [animationDurationStr, setAnimationDurationStr] = useState<string>('200');

    // 文案与类型
    const [title, setTitle] = useState<string>('提示');
    const [message, setMessage] = useState<string>('这是一个提示信息。');
    const [dialogType, setDialogType] = useState<DialogType>('info');
    const [confirmText, setConfirmText] = useState<string>('确定');
    const [cancelText, setCancelText] = useState<string>('取消');

    // 结果展示
    const [lastAlert, setLastAlert] = useState<string>('-');
    const [lastConfirm, setLastConfirm] = useState<string>('-');
    const [lastProgrammatic, setLastProgrammatic] = useState<string>('-');

    const customActions: DialogAction[] = useMemo(() => [
        { text: '继续', value: 'continue', role: 'default' },
        { text: '删除', value: 'delete', role: 'destructive' },
        { text: '取消', role: 'cancel' },
    ], []);

    const commonOptions = useMemo(() => ({
        title,
        message,
        type: dialogType,
        blocking,
        cancelable,
        maskColor,
        animationDuration: Number.isFinite(parseInt(animationDurationStr)) ? parseInt(animationDurationStr) : 200,
    }), [title, message, dialogType, blocking, cancelable, maskColor, animationDurationStr]);

    // 基础用法：alert（无返回值）
    const runAlert = async () => {
        await Dialog.alert({
            ...commonOptions,
            confirmText,
        });
        setLastAlert(`已完成：${confirmText}`);
    };

    // 基础用法：confirm（返回布尔）
    const runConfirm = async () => {
        const ok = await Dialog.confirm({
            ...commonOptions,
            confirmText,
            cancelText,
        });
        setLastConfirm(ok ? '确认（true）' : '取消（false）');
    };

    // 自定义 actions：仅展示 UI（show）
    const showCustomActions = () => {
        Dialog.show({
            ...commonOptions,
            actions: customActions,
        });
    };

    // 编程取消：展示后自动取消
    const showThenCancel = () => {
        Dialog.show(commonOptions);
        setTimeout(() => {
            setLastProgrammatic('编程取消（false）');
            Dialog.cancel();
        }, 1200);
    };

    // 编程提交：展示后自动提交指定值
    const showThenSubmit = () => {
        Dialog.show(commonOptions);
        setTimeout(() => {
            setLastProgrammatic('编程提交（"auto"）');
            Dialog.submit('auto');
        }, 1200);
    };

    return (
        <Layout.Page
            headerShown
            headerProps={{ title: 'Dialog 测试', backVisible: true }}
            padding={16}
            scrollable
            testID="DialogTestScreen"
        >
            {/* 行为开关 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>行为开关</UI.Text>
                    <View style={styles.row}>
                        <UI.Text variant="body2" color="textSecondary">遮罩点击取消（cancelable）</UI.Text>
                        <Switch value={cancelable} onValueChange={setCancelable} testID="switch-cancelable" />
                        <UI.Text variant="body2" color="textSecondary">阻塞底层交互（blocking）</UI.Text>
                        <Switch value={blocking} onValueChange={setBlocking} testID="switch-blocking" />
                    </View>
                </Layout.Card>
            </View>

            {/* 文案与样式 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>文案与样式</UI.Text>
                    <View style={styles.col}>
                        <UI.Text children={'标题（title）'} />
                        <UI.Input
                            value={title}
                            onChangeText={setTitle}
                            placeholder="提示"
                            testID="input-title"
                        />
                        <UI.Text children={'消息（message）'} />
                        <UI.Input
                            value={message}
                            onChangeText={setMessage}
                            placeholder="这是一个提示信息。"
                            testID="input-message"
                        />
                        <UI.Text children={'遮罩颜色（maskColor）'} />
                        <UI.Input
                            value={maskColor}
                            onChangeText={setMaskColor}
                            placeholder="rgba(0,0,0,0.45)"
                            testID="input-mask-color"
                        />
                        <UI.Text children={'动画时长（ms）'} />
                        <UI.Input
                            value={animationDurationStr}
                            onChangeText={setAnimationDurationStr}
                            placeholder="200"
                            keyboardType="numeric"
                            testID="input-animation-duration"
                        />
                    </View>
                </Layout.Card>
            </View>

            {/* 类型选择 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>类型（type）</UI.Text>
                    <View style={styles.row}>
                        {typeList.map((t) => (
                            <UI.Button
                                key={t}
                                title={t}
                                variant={dialogType === t ? 'primary' : 'outline'}
                                onPress={() => setDialogType(t)}
                                testID={`btn-type-${t}`}
                            />
                        ))}
                    </View>
                </Layout.Card>
            </View>

            {/* 基础用法：alert / confirm */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>基础用法</UI.Text>
                    <View style={styles.row}>
                        <UI.Text children={'确认按钮文案（confirmText）'} />
                        <UI.Input
                            value={confirmText}
                            onChangeText={setConfirmText}
                            placeholder="确定"
                            testID="input-confirm-text"
                        />
                        <UI.Text children={'取消按钮文案（cancelText）'} />
                        <UI.Input
                            value={cancelText}
                            onChangeText={setCancelText}
                            placeholder="取消"
                            testID="input-cancel-text"
                        />
                    </View>
                    <View style={[styles.row, { marginTop: 12 }]}>
                        <UI.Button title="Alert" onPress={runAlert} fullWidth testID="btn-alert" />
                        <UI.Button title="Confirm" onPress={runConfirm} fullWidth testID="btn-confirm" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>结果：</UI.Text>
                        <UI.Text variant="body1" color="text" testID="text-alert-result">Alert：{lastAlert}</UI.Text>
                        <UI.Text variant="body1" color="text" testID="text-confirm-result">Confirm：{lastConfirm}</UI.Text>
                    </View>
                </Layout.Card>
            </View>

            {/* 自定义 actions 与编程控制 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>自定义 actions / 编程控制</UI.Text>
                    <UI.Text variant="caption" color="subtext" mb={8}>
                        show(options) 仅展示 UI；使用 Dialog.cancel()/Dialog.submit(value) 可进行编程控制。
                    </UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="展示自定义 actions（show）" onPress={showCustomActions} fullWidth testID="btn-show-custom-actions" />
                        <UI.Button title="展示后自动取消" variant="outline" onPress={showThenCancel} fullWidth testID="btn-show-then-cancel" />
                        <UI.Button title="展示后自动提交值" variant="outline" onPress={showThenSubmit} fullWidth testID="btn-show-then-submit" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>编程结果：</UI.Text>
                        <UI.Text variant="body1" color="text" testID="text-programmatic-result">{lastProgrammatic}</UI.Text>
                    </View>
                </Layout.Card>
            </View>
        </Layout.Page>
    );
};

export default DialogTestScreen;